package com.sservice.service.service;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.sservice.common.Constants;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

/**
 * 阿里云oss 工具
 * Created by suweiming on 2018/5/12.
 */
@Component
public class ALiYunOSSUtil {
    static Logger logger = Logger.getLogger(ALiYunOSSUtil.class);

    // endpoint是访问OSS的域名。如果您已经在OSS的控制台上 创建了Bucket，请在控制台上查看域名。
    // 如果您还没有创建Bucket，endpoint选择请参看文档中心的“开发人员指南 > 基本概念 > 访问域名”，
    // 链接地址是：https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html?spm=5176.docoss/user_guide/endpoint_region
    // endpoint的格式形如“http://oss-cn-hangzhou.aliyuncs.com/”，注意http://后不带bucket名称，
    // 比如“http://bucket-name.oss-cn-hangzhou.aliyuncs.com”，是错误的endpoint，请去掉其中的“bucket-name”。
    private static String endpoint = Constants.aliYunOssEndpoint;
    private static OSSClient ossClient = null;
    // 创建和查看访问密钥的链接地址是：https://ak-console.aliyun.com/#/。
    // 注意：accessKeyId和accessKeySecret前后都没有空格，从控制台复制时请检查并去除多余的空格。
    private static String accessKeyId = Constants.aliYunOssAccessKeyId;
    private static String accessKeySecret = Constants.aliYunOssKeySecret;

    // Bucket命名规范如下：只能包括小写字母，数字和短横线（-），必须以小写字母或者数字开头，长度必须在3-63字节之间。
    private static String bucketName = Constants.aliYunOssBucket;//

    public ALiYunOSSUtil() {
        this.endpoint = Constants.aliYunOssEndpoint;
        this.accessKeyId = Constants.aliYunOssAccessKeyId;
        this.accessKeySecret = Constants.aliYunOssKeySecret;
    }

    public static OSSClient intOssClient() {

        bucketName = Constants.aliYunOssBucket;
        endpoint = Constants.aliYunOssEndpoint;
        accessKeyId = Constants.aliYunOssAccessKeyId;
        accessKeySecret = Constants.aliYunOssKeySecret;

        if (ossClient == null) {
            ossClient = new OSSClient(
                    Constants.aliYunOssEndpoint
                    , accessKeyId, accessKeySecret);
        }
        return ossClient;
    }

    /**
     * oss 上传
     *
     * @param inputStream 输入流
     * @param name        名称 test.jpg
     * @param path        相对路径 /thumbnail/2017-09
     * @return
     */
    public static String upload(InputStream inputStream, String name, String path) {
        // 生成OSSClient，您可以指定一些参数，详见“SDK手册 > Java-SDK > 初始化”，
        // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/init.html?spm=5176.docoss/sdk/java-sdk/get-start
        OSSClient ossClient = intOssClient();
        try {
            // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
            String name1 = path + name;
            ossClient.putObject(bucketName, name1, inputStream);
            return ossClient.getObject(bucketName, name1).getResponse().getUri().toString();
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//            ossClient = null;
        }
        return null;
    }

    public static int count(String path) {
        OSSClient ossClient = intOssClient();
        final int maxKeys = 1000;
        try {
            ObjectListing objectListing = ossClient.listObjects(
                    new ListObjectsRequest(bucketName).withPrefix(path).withMaxKeys(maxKeys)
            );
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            return sums.size();
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            ossClient = null;
        }
        return 0;
    }
}